var gMyWidgets;
var gNewWidget;
var gCategoriesList;
var gCurrentWidgetId;
var gEditWidget;


function UserPageBuilder () {
	PageBuilder.call(this);
}

UserPageBuilder.prototype = new PageBuilder();

UserPageBuilder.prototype.constructor = UserPageBuilder;

UserPageBuilder.prototype.build = function () {
	$("#widgetname_label").html(getDisplayString("widgetname_caption"));
	$("#embed_label").html(getDisplayString("embed_caption"));
	$("#iconchooser_label").html(getDisplayString("iconchooser_caption"));
	$("#widgetdescription_label").html(getDisplayString("widgetdescription_caption"));
	$("#widgetwidth_label").html(getDisplayString("widgetwidth_caption"));
	$("#widgetheight_label").html(getDisplayString("widgetheight_caption"));
	$("#submit_label").html(getDisplayString("submitbutton_caption"));
}



$(document).ready(function(){
	setLogin();
	buildPage(new UserPageBuilder() );
	gNewWidget = getQueryVariable("WidgetId");
	$("#searchText").on('keydown', function(e) {
		if ( e.which == 13 ) {
			e.preventDefault();
			searchStore();
		}
	});
	var iconLabel = getDisplayString("label_icon");
	var titleLabel = getDisplayString("label_title");
	var dateLabel = getDisplayString("label_date");
	var viewLabel = getDisplayString("label_view");
	var publishedLabel = getDisplayString("label_published");
	var categoriesLabel = getDisplayString("label_categories");
	var editLabel = getDisplayString("label_edit");
	var deleteLabel = getDisplayString("label_delete");
	
	$("#widgetList").jqGrid({
		datatype: "local",
		height: 300,
		autowidth: true,
		// icon title date view publish edit delete
		colNames:[iconLabel,titleLabel, dateLabel, viewLabel, publishedLabel, categoriesLabel, editLabel, deleteLabel],
		colModel:[
			{name:'icon', index:'icon', width:60},
			{name:'title', index:'title', width:180},
			{name:'date', index:'date', width:180},
			{name:'view', index:'view', width:60},
			{name:'published', width:60},
			{name:'categories', width:60},
			{name:'edit',width:60},
			{name:'delete',width:60}
		],
		multiselect: false,
		caption: getDisplayString("widgetlist_caption"),
		pager:'#pager'
	});
	$("#widgetList").navGrid('#pager',{edit:false,add:false,del:false,search:false});
	$("#widgetList").navButtonAdd('#pager',{
   			caption:getDisplayString("newwidget_caption"), 
   			buttonicon:"ui-icon-plus", 
   			onClickButton: newWidget, 
   			position:"last"
	});
	
	// grid resizer
	$(window).resize(function(e) {
        var newPageWidth = $("#page").width();
		$("#widgetList").jqGrid('setGridWidth', newPageWidth);

    });
	gCurrentWidgetId = 0;
	
	getUserWidgetProfiles();
	getCategoriesList();
	
	$("#viewDialog").dialog({
		autoOpen: false,
		modal: true
	});
	
	$("#categoriesDialog").dialog({
		autoOpen:false,
		modal: true
	});

	
	$("#editDialog").dialog({
		autoOpen:false,
		modal:true,
		width:700
	});
	
	
	getIconList ( "web", buildWebIconChooser );

});


function buildWebIconChooser ( iconList ) {
	buildIconChooser ( iconList, "web_icon_chooser");
}






function getUserWidgetProfiles() {
	var u = getUser();
	if ( u == null ) {
		alert ("User must be logged in.");
		return;
	}
	var uri = store_rest_url + "/users/widgets";
	var authString = getBase64Authentication();
	$.ajax({
		type: "GET",
		url: uri,
		beforeSend: function(xhr) {
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		dataType: "text",
		success: displayUserWidgets
	});
}


function displayUserWidgets(jsonString) {
	var widgetList = $.parseJSON(jsonString);
	gMyWidgets = widgetList;
	var newWidgetRowID = 0;
	
	$("#widgetList").jqGrid('clearGridData');
	for (var i = widgetList.length-1; i>=0; i--) {
		var widget = widgetList[i];
		
		if (widget.icon == null ) {
			widget.icon = "img/default_widget_icon.png";
		}
		var checkIcon;
		if (widget.publish_level > 1 ) {
			checkIcon = '<img src="img/checked.png" width="16" height="16"/>';
		}
		else {
			checkIcon = '<img src="img/not_checked.png" width="16" height="16"/>';
		}
		var iconString = '<a href="#" onclick="showWidgetView('+widget.id+')"><img src="'+widget.icon+'" alt="'+widget.name+'" width="16" height="16"/></a>';
		var viewString = '<a href="#" onclick="viewWidget('+widget.id+')"><img src="img/view_icon.png" width="16" height="16"/></a>';
		var publishString = '<a href="#" onclick="togglePublished('+widget.id+','+widget.publish_level+')">'+checkIcon+'</a>';
		var categoriesLength;
		if ( widget.categories ) {
			categoriesLength = widget.categories.length;
		}
		else {
			categoriesLength = 0;
		}
		var categoriesString = categoriesLength+'&nbsp;<button onClick="viewCategories('+widget.id+')">Categories</button>';
		
		var editString;
		if ( widget.builder == "embed" || widget.builder == "webaddress" ) {
			editString = '<a href="#" onclick="editWidget('+widget.id+')"><img src="img/pencil.png" width="16" height="16"/></a>';
		}
		else {
			editString = '<img src="img/pencil_faded.png" width="16" height="16"/>';
		}
		
		var deleteString = '<a href="#" onclick="deleteWidget('+widget.id+',\''+widget.name+'\')"><img src="img/delete_icon.png" width="16" height="16"/></a>';
		var widgetData = { icon:iconString,
							title:widget.name,
							date:widget.created,
							view:viewString,
							published:publishString,
							categories:categoriesString,
							edit:editString,
							delete:deleteString
		};
		$("#widgetList").jqGrid('addRowData', widget.id, widgetData); 
		if ( gNewWidget != null ) {
			if ( widget.id == gNewWidget ) {
				newWidgetRowId = i+1;
			}
		}
		
	//var lastSelectedWidget = getCookie("lastSelectedWidget");
	//selectWidget(lastSelectedWidget);
	}
	if ( gNewWidget != null ) {
		$("#widgetList").jqGrid('setSelection', newWidgetRowId, true);
		viewWidget(gNewWidget);
	}
}


// respond to a click on view widget

function viewWidget ( widget_id ) {
	gNewWidget = null;
	$.ajax({
		type:"GET",
		url:store_rest_url+"/widgets/"+widget_id,
		dataType: "text",
		success: showWidget
	});
}


function showWidget ( jsonString ) {
	var w = $.parseJSON(jsonString);
	// get the width from the iframe info
	//var render = w.renderInfo;
	
	$("#viewContents").html(w.renderInfo);
	var wid = $("#viewContents > iframe").width() + 34;
	$("#viewDialog").dialog("option","title", w.widgetProfile.name );
	$("#viewDialog").dialog("option","width", wid );
	$("#viewDialog").dialog("open");
}


function getCategoriesList() {
	gCategoriesList = null;
	$.getJSON(store_rest_url + "/categories", function(data){
		gCategoriesList = data;
	});
}

function viewCategories(widget_id) {
	var selects = '';
	var widget = getWidgetFromList(widget_id);
	gCurrentWidgetId = widget_id;
	if ( widget == null ) {
		$('#categoriesContent').html('No widget for id: '+widget_id);
		$("#categoriesDialog").dialog("open");
		return;
	}
	if ( gCategoriesList == null ) {
		$('#categoriesContent').html('Categories not loaded');
		$("#categoriesDialog").dialog("open");
		return;
	}
	for ( var i = 0; i < gCategoriesList.length; i++ ) {
		var group = gCategoriesList[i];
		for (var j=0; j<group.length; j++) {
			var category = group[j];
			var selected = '';
			if ( widget.categories != null ) {
				for ( var n=0; n<widget.categories.length; n++ ) {
					if ( widget.categories[n].id == category.id ) {
						selected = 'selected="selected"';
					}
				}
			}
			selects += '<option value="'+category.id+'" '+selected+'>'+category.title+'</option>';
		}
	}
	$("#categorySelect").html(selects);
	$("#categoriesDialog").dialog("option", "minHeight", 400);
	$("#categoriesDialog").dialog("option","title", "Categories" );

	$("#categoriesDialog").dialog("open");
	$("#categorySelect").multipleSelect({
		onClick: function(view) {
			var category_id = view.value;
			if ( view.checked ) {
				addCategoryToWidget ( category_id, gCurrentWidgetId );
			}
			else {
				removeCategoryFromWidget ( category_id, gCurrentWidgetId );
			}
        }
	});

}


function addCategoryToWidget ( category_id, widget_id ) {
	var uri = store_rest_url+"/widgets/categories/add/"+widget_id+"/"+category_id;
	$.ajax({
		type:"POST",
		url:uri,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization","Basic "+authString);
		},
		dataType: "text",
		success: showMessage,
		error: showError
	});
}


function removeCategoryFromWidget ( category_id, widget_id ) {
	var uri = store_rest_url+"/widgets/categories/remove/"+widget_id+"/"+category_id;
	$.ajax({
		type:"DELETE",
		url:uri,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization","Basic "+authString);
		},
		dataType: "text",
		success: showMessage,
		error: showError
	});	
}

function showMessage ( result ) {
	var message = $.parseJSON(result);
	if ( message.message == "OK" ) {
		getUserWidgetProfiles();
		return;
	}
	alert ( message.message );
}


function showError ( jqXHR, textStatus, errorThrown ) {
	alert (jqXHR.responseText );
}



function getWidgetFromList ( widget_id ) {
	for (var i=0; i<gMyWidgets.length; i++ ) {
		var widget = gMyWidgets[i];
		if ( widget.id == widget_id ) {
			return widget;
		}
	}
	return null;
}


// at the moment we only have two publish levels, 2 is published below this is unpublished

function togglePublished(widgetId, currentLevel) {
	var newLevel = 2;
	if ( currentLevel == 2 ) {
		newLevel = 0;
	}

	
	var uri = store_rest_url+"/widgets/publish_level/"+widgetId+"/"+newLevel;
	$.ajax({
		type:"PUT",
		url:uri,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		dataType: "text",
		success:publishLevelSet,
		error:publishLevelError
	});
}


function publishLevelSet (jsonString) {
	var msg = $.parseJSON(jsonString);
	if ( msg.message == "OK") {
		getUserWidgetProfiles();
	}
	else {
		alert (getDisplayString("widget_publish_level_not_set"));
	}
}

function publishLevelError ( jqXHR, textStatus, errorThrown ) {
	alert (getDisplayString("widget_publish_level_not_set"+": "+jqXHR.reponseText));
}


// can only edit widgets that have been created by the embed tool

function editWidget(widgetId) {
	var rest = store_rest_url+"/widgets/"+widgetId;
	$.ajax({
		type:"GET",
		url:rest,
		dataType: "json",
		success: showEditData,
		error: widgetGetFail
	});
}



function showEditData ( widget ) {
	var widgetProfile = widget.widgetProfile;
	gEditWidget = widgetProfile;
	$("#buildertype").val(widgetProfile.builder);
	$("#widgetname").html(widgetProfile.name);
	$("#widgetdescription").val(widgetProfile.description);
	
	if ( widgetProfile.builder == "webaddress" ) {
		$("#embed_label").html(getDisplayString("edit_webaddress_caption"));
	}
	
	var width = 400;
	var height = 400;
	var embed = "";
	
	if ( widgetProfile.meta_data != null || widgetProfile.meta_data.length > 0 ) {
		var metaDataEncoded = widgetProfile.meta_data;
		metaDataEncoded = metaDataEncoded.replace(/\s+/g," ");
		var metaData = $.parseJSON(metaDataEncoded);
		width = metaData.width;
		height = metaData.height;
		embed = metaData.html;
	}
	$("#widgetwidth").val(width);
	$("#widgetheight").val(height);
	
	$("#embed").html(embed);
	$("#editDialog").dialog("open");
	
}


function widgetGetFail ( jqXHR, textStatus, errorThrown ) {
	alert (getDisplayString("widget_get_failed"+": "+jqXHR.reponseText));
}




// respond to clicking the delete button for a widget

function deleteWidget(widgetId, widgetName) {
	if (widgetName == "WidgetStore") {
		alert(getDisplayString("widget_delete_prohibited"));
		return;
	}
	var result = confirm("Are you sure you wish to delete this widget? This action cannot be undone!");
	if ( result ) {
		var u = getUser();
		if ( u == null ) {
			alert("You must be logged in to delete widgets");
			return;
		}
		var uri = store_rest_url+"/widgets/delete/"+widgetId;
		$.ajax({
			type:"DELETE",
			url:uri,
			beforeSend: function(xhr) {
				var authString = getBase64Authentication();
				xhr.setRequestHeader("Authorization", "Basic "+authString);
			},
			dataType:"text",
			success:widgetDeleted,
			error:widgetNotDeleted
		});
	}
}

function widgetDeleted(jsonString) {
	var msg = $.parseJSON(jsonString);
	if ( msg.message == "OK" ) {
		getUserWidgetProfiles();
	}
	else {
		alert ("Unable to delete widget.  The message from the server is: "+msg.message);
	}
}

function widgetNotDeleted(jqXHR, textStatus, errorThrown ) {
	alert ("Unable to delete widget.  The message from the server is: "+jqXHR.responseText);
}


// respond to clicking the global add button

function newWidget()
{
	goToWidgetCreator();
}

// update


/*
	$("#embedform").ajaxForm({
		dataType: "text",
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		error: embedFailed,
		success: embedUpdated
	});
	*/

function updateEmbed(){
	var embedData = new Object();
	embedData.widgetname = $("#widgetname").html();
	embedData.widgetdescription = $("#widgetdescription").val();
	embedData.embed = $("#embed").val();
	embedData.widgetwidth = $("#widgetwidth").val();
	embedData.widgetheight = $("#widgetheight").val();
	var iconName = "";
	if ( gEditWidget.icon == null ) {
		iconName = "default_widget.png";
	}
	else {
		var index = gEditWidget.icon.lastIndexOf("/");
		if ( index == -1 ) {
			iconName = "default_widget_png";
		}
		else {
			iconName = gEditWidget.icon.substring(index+1);
		}
	}
	embedData.icon = iconName; //$("input:radio[name=icon]:checked").val();
	embedData.builder = gEditWidget.builder;
	$("#editDialog").dialog("close");
	var u = getUser();
	var uri = store_rest_url+"/creator/embed";
	$.ajax({
		url:uri,
		type:"PUT",
		data:embedData,
		beforeSend: function(xhr) {
			var authString = getBase64Authentication();
			xhr.setRequestHeader("Authorization", "Basic "+authString);
		},
		error: embedFailed,
		success: embedUpdated
	});
	//$("#embedform").attr('action', uri);
	//$("embedformuser").val(u.username);
	//$("#embedform").submit();
}

function embedUpdated() {
	getUserWidgetProfiles();
}


function embedFailed() {
	alert("Failed");
}